from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *
import datetime

# Create your views here.


class ParkView(APIView):
    def post(self, request):
        name = request.data.get('name')
        title = request.data.get('title')
        park_id = request.data.get('park_id')
        user = UserModel.objects.filter(name=name, title=title).first()
        if not user:
            user = UserModel.objects.create(name=name, title=title)
        else:
            record = RecordModel.objects.filter(user_id=user.id, money=None).first()
            if record:
                return Response({'msg': '车已停在小区', 'code': 200})
            else:
                RecordModel.objects.create(park_id=park_id, user_id=user.id)
                return Response({'msg': '进入小区, 开始计时', 'code': 200})

    def get(self, request):
        set = ParkModel.objects.all()
        return Response(ParkSer(set, many=True).data)


class RecordView(APIView):
    def get(self, request):
        park_id = request.GET.get('park_id')
        title = request.GET.get('title')
        if park_id:
            set = RecordModel.objects.filter(park_id=park_id, money=None).order_by('-start')
        elif title:
            set = RecordModel.objects.filter(user__title=title).exclude(money=None).order_by('-start')
        else:
            set = RecordModel.objects.exclude(money=None).order_by('-start')
        return Response(RecordSer(set, many=True).data)

    def put(self, request):
        record_id = request.data.get('record_id')
        record = RecordModel.objects.filter(id=record_id).first()
        user = UserModel.objects.filter(id=record.user_id).first()
        price = PriceModel.objects.filter(park_id=record.park_id, level=record.user.level).first().price
        time = round((datetime.datetime.now() - record.start).total_seconds() / 3600)
        money = round(price * time)
        record.time = time
        record.money = money
        record.price = price
        record.save()
        user.number += 1
        user.money += money
        user.save()
        return Response({'msg': 'OK', 'code': 200})


class UserView(APIView):
    def put(self, request):
        user_id = request.data.get('user_id')
        user = UserModel.objects.filter(id=user_id).first()
        user.level = 1
        user.save()
        return Response({'msg': '升级成功', 'code': 200})